package Game.Online 
{
	import flash.events.Event;
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	import Game.GameElements.GameObject;
	import Game.GameElements.Tank;
	import Game.Online.Messages.Message;
	import Game.Online.Messages.MessageDoRocket;
	import Game.Online.Messages.MessageLogIn;
	import Game.Online.Messages.MessagesDefs;
	import Game.Online.Messages.MessagesHandler;
	/**
	 * ...
	 * @author Yevgeniy Logachev
	 */
	public class OnlineManager 
	{
		private static const s_instance:OnlineManager 	= new OnlineManager();
		private static var m_connection:Connection			= null;
		
		private static var m_isLogin:Boolean				= false;
				
		public function OnlineManager() 
		{
			if (s_instance == null)
			{
				trace ("OnlineManager initialized");
			}
			else
			{
				trace("ERROR: Already existing instance in Singleton");
				throw new Error("Already existing instance in Singleton");
			}
		}
		
		public static function get instance():OnlineManager
		{
			return s_instance;
		}
		
		public function logIn():void
		{
			m_connection = new Connection("10.60.8.118", 10000);
		}
		
		public function onConnect():void
		{
			var msg:MessageLogIn = new MessageLogIn();
			m_connection.sendMessage(msg);
		}
		
		public function get connection():Connection
		{
			return m_connection;
		}
		
		public function get isLoggedIn():Boolean
		{
			if (!Settings.enableOnline)
			{
				return true;
			}
			
			return m_isLogin;
		}
		
		public function onLogIn(msg:MessageLogIn):void
		{	
			trace("User id: " + msg.id);
			if(msg.id == m_connection.id)
			{
				if (!m_isLogin)
				{
					m_isLogin = true;
					var tank:Tank = new Tank(msg.posX, msg.posY, 0, 1, Tank.TYPE_GAME_PLAYER);
					tank.playerName = msg.name;
				}
			}
			else
			{
				for each(var gameObject:GameObject in GameObject.gameObjects)
				{
					if ((gameObject is Tank) && (gameObject as Tank).m_remoteId == msg.id)
					{
						return;
					}
				}
				
				var remote:Tank = new Tank(msg.posX, msg.posY, 0, 1, Tank.TYPE_REMOTE_PLAYER);
				remote.m_remoteId = msg.id;
				remote.playerName = msg.name;
			}
		}
		
		public function doRocket(msg:MessageDoRocket):void
		{	
			trace("User id: " + msg.id);
			if(msg.id != m_connection.id)
			{
				for each(var gameObject:GameObject in GameObject.gameObjects)
				{
					if ((gameObject is Tank) && (gameObject as Tank).m_remoteId == msg.id)
					{
						(gameObject as Tank).doRocket();
					}
				}
			}
		}
	}
}
